package com.yinhe.controller.login;

import com.alibaba.fastjson.JSONObject;
import com.yinhe.model.User;
import com.yinhe.service.AsyncTaskService;
import com.yinhe.util.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// @Controller
@Slf4j
@Api(tags="登录权限验证模块")
@RequestMapping("/nologin")
public class LoginController {



    @Autowired
    private AsyncTaskService asyncTaskService;

    @Autowired
    private RedisUtils redisUtils;


    @RequestMapping(value = "/selectUserById", produces = "application/json; charset=utf-8",method = RequestMethod.GET)
    @ResponseBody
    public String selectUserById() throws Exception {
        log.info("用户查询");
        JSONObject json = new JSONObject();
        json.put("code","201");
        json.put("msg","查询失败");
        // User user = userService.selectUser(1);
        User user = null;
        if(user!=null){
            json.put("code","200");
            json.put("msg","查询成功");
        }
        return json.toJSONString();
    }

    @ApiOperation("用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user",//参数名字
                    value = "这是一个用户的对象",//参数的描述
                    required = true,//是否必须传参数，true是
                    paramType = "body")//参数类型 body代表json
    })
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public String logintUser(HttpServletRequest request, HttpServletResponse response, @RequestBody User user) throws Exception {
        log.info("用户登陆接口，当前登录人："+user.getUsername());
        JSONObject json = new JSONObject();
        json.put("code","201");
        String currentPassword =  DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        // User dataBaseUser = getUserByPassword(user);
        User dataBaseUser = new User();
        String msg = "登录失败";
        if(dataBaseUser==null){
            log.info("用户账号不存在！");
            msg = "用户账号不存在！";
        }else if(!currentPassword.equals(dataBaseUser.getPassword())){
            log.info("用户密码错误！");
            msg = "用户密码错误！";
        }else {
            json.put("code","200");
            msg = "登录成功";
            HttpSession session = request.getSession(false);
            if(session!=null){
                //注销原session，为的是重置sessionId
                session.invalidate();
                //将临时map中的数据转移至新session

            }
            session = request.getSession();
            session.setAttribute("user",user);
            json.put("sessionId",session.getId());
            json.put("data",dataBaseUser);
            Cookie cookie=new Cookie("JSESSIONID", session.getId());
            cookie.setPath("/");
            response.addCookie(cookie);

        }
        json.put("msg",msg);
        return json.toJSONString();
    }

    @RequestMapping(value = "/testAsyn",method = RequestMethod.GET)
    @ResponseBody
    public String testAsyn() throws Exception {
        log.info("开始测试异步任务");
        JSONObject json = new JSONObject();
        json.put("code","200");
        json.put("msg","测试异步成功");
        for (int i = 0; i < 200; i++) {
            asyncTaskService.executeAsyncTask(i);
        }
        return json.toJSONString();
    }
    @RequestMapping(value = "/getRedisValueByKey/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String hello(@PathVariable(value = "id") String id){
        log.info("开始测试redis获取数据");
        JSONObject json = new JSONObject();
        json.put("code","201");
        json.put("msg","测试从redis获取数据失败");
        json.put("data","");
        String str = null;

        try {
            //查询缓存中是否存在
            boolean hasKey = redisUtils.exists(id);
            str = "";
            if(hasKey){
                //获取缓存
                Object object =  redisUtils.get(id);
                log.info("从缓存获取的数据"+ object);
                str = object.toString();
            }
            json.put("code","200");
            json.put("msg","测试从redis获取数据成功");
            json.put("data",str);
        } catch (Exception e) {
            log.error("查询redis键值异常：原因如下："+e.getMessage());
        }
        return json.toJSONString();
    }

    @RequestMapping(value = "/setRedisValueByKey/{id}/{value}",method = RequestMethod.GET)
    @ResponseBody
    public String setRedisValueByKey(@PathVariable(value = "id") String id,@PathVariable(value = "value") String value){
        log.info("开始测试redis获取数据");
        JSONObject json = new JSONObject();
        json.put("code","201");
        json.put("msg","测试创建redis键值对失败");
        json.put("data","");
        try {
            //查询缓存中是否存在
            boolean bo = redisUtils.set(id,value);
            json.put("code","200");
            json.put("msg","测试创建redis键值对成功");
            json.put("data",bo);
        } catch (Exception e) {
            log.error("创建redis键值异常：原因如下："+e.getMessage());
        }
        return json.toJSONString();
    }




}